<template>
  <div>
    <div class="images">
      <div class="item-video" v-if="cameraList[0]">
        <video
          ref="video0"
          width="100%"
          height="100%"
          autoplay
          style="border-radius: 10px"
        ></video>
      </div>
      <div class="item-video" v-if="cameraList[1]">
        <video
          ref="video1"
          width="100%"
          height="100%"
          autoplay
          style="border-radius: 10px"
        ></video>
      </div>
      <div class="item-video" v-if="cameraList[2]">
        <video
          ref="video2"
          width="100%"
          height="100%"
          autoplay
          style="border-radius: 10px"
        ></video>
      </div>
      <div class="item-video" v-if="cameraList[3]">
        <video
          ref="video3"
          width="100%"
          height="100%"
          autoplay
          style="border-radius: 10px"
        ></video>
      </div>
    </div>
  </div>
</template>

<script>
let streamObjectList = [];
export default {
  name: "CameraCaptureTask",
  data() {
    return {
      navigator: null,
      cameraList: [],
      photos: [],
    };
  },
  mounted() {
    navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia; // 获取媒体对象（这里指摄像头）

    this.playCamera(null, null, true).then(() => {
      this.initImages();
    });
  },
  methods: {
    photograph() {
      const photos = [];
      this.cameraList.forEach((camera, index) => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        const videoElement = this.$refs[`video${index}`];
        canvas.width = videoElement.offsetWidth;
        canvas.height = videoElement.offsetHeight;
        ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
        const image = canvas.toDataURL("image/png");
        photos.push(image);
        if (photos.length === this.cameraList.length) {
          this.$emit("success", photos);
        }
      });
    },
    initImages() {
      navigator.mediaDevices.enumerateDevices().then((mediaDevices) => {
        this.cameraList = mediaDevices.filter(
          (device) => device.kind === "videoinput"
        );

        this.$nextTick(() => {
          streamObjectList = [];
          this.cameraList.forEach((camera, index) => {
            this.playCamera(camera.deviceId, this.$refs[`video${index}`]);
          });
        });
      });
    },
    playCamera(deviceId, videoEle, env = null) {
      return new Promise((resolve, reject) => {
        // 组装数据(固定格式)
        let constraints = {};
        if (!env) {
          constraints = {
            video: {
              deviceId: {
                exact: deviceId, // 要切换到的设备ID
              },
            },
            audio: false,
          };
        } else {
          constraints = {
            video: {
              facingMode: "environment",
            },
            audio: false,
          };
        }

        navigator.mediaDevices
          .getUserMedia(constraints) // 传入要切换到的设备
          .then((stream) => {
            streamObjectList.push({
              stream,
              videoEle,
            });
            if (videoEle) {
              videoEle.srcObject = stream;
            }
            resolve();
          })
          .catch((error) => {
            reject();
            this.$alert(
              "您关闭了摄像头权限，需要在浏览器设置中设置后可继续",
              "系统提示",
              {
                confirmButtonText: "确定",
                callback: (action) => {
                  this.$emit("close");
                },
              }
            );
          });
      });
    },
  },
  beforeDestroy() {
    // 关闭摄像头
    streamObjectList.forEach((item, index) => {
      item.stream.getTracks().forEach(function (track) {
        track.stop();
      });
      item.stream.getVideoTracks()[0].stop();
      item.videoEle.srcObject = null;
    });
    streamObjectList = [];
  },
};
</script>

<style lang="scss" scoped>
.images {
  display: flex;
  justify-content: center;
}
.item-video {
  width: 100%;
  border: 1px solid #eaeaea;
  margin-bottom: 10px;
  border-radius: 10px;
  // margin-left: 20px;
}
.left-right {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
